<template>
  <span>{{ currentNum }}</span>
</template>

<script>
import { myAnimatiton } from "../../../utils/util";
export default {
  name: 'AnimateNumber',
  props: {
    // 变化的数字
    num: {
      type: Number
    },
    // 数字格式化处理，默认保留2位小数
    format: {
      type: Function,
      default: (val) => val.toFixed(2)
    },
    // 动画持续时间(ms)，默认1000ms
    duration: {
      type: Number,
      default: 1000
    },
    // 动画首次加载延迟时间（ms），默认0
    delay: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      currentNum: ''
    }
  },
  watch: {
    num(newVal, oldVal) {
      this.startAnimate(newVal, oldVal);
    }
  },
  mounted() {
    if(this.delay) {
      setTimeout(() => {
        this.startAnimate();
      }, this.delay);
    } else {
      this.startAnimate();
    }
  },
  methods: {
    startAnimate(newVal = this.num, oldVal = 0) {
      myAnimatiton(this.duration, oldVal, newVal, (val) => {
        this.currentNum = this.format(val);
      })
    }
  }
}
</script>